package com.example.forum.controller;


import com.example.forum.common.AppResult;
import com.example.forum.common.ResultCode;
import com.example.forum.config.AppConfig;
import com.example.forum.exception.ApplicationException;
import com.example.forum.model.Message;
import com.example.forum.model.User;
import com.example.forum.services.IMessageService;
import com.example.forum.services.IUserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Param;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Objects;

@Slf4j
@Tag(name = "站内信")
@RestController
@RequestMapping("/message")
public class MessageController {


    @Resource
    private IMessageService messageService;

    @Resource
    private IUserService userService;

    @Operation(summary = "发送站内信")
    @PostMapping("/send")
    public AppResult send (HttpServletRequest request,
    @Param("接收者id") @RequestParam("receiveUserId") @NonNull Long receiveUserId,
            @Param("内容") @RequestParam("content") @NonNull String content) {



        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        // 校验用户是否禁言
        if (user.getState() == 1) {
            // 用户已禁言
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_BANNED));
        }

        // 不能给自己发站内信
        if (Objects.equals(user.getId(), receiveUserId)) {
            return AppResult.failed("不能给自己发送");
        }

        // 校验接收者是否存在
        User receiveUser = userService.selectById(receiveUserId);
        if (receiveUser == null || receiveUser.getDeleteState() == 1) {
            return AppResult.failed("接收者状态异常");
        }

        Message message = new Message();
        message.setPostUserId(user.getId());
        message.setReceiveUserId(receiveUserId);
        message.setContent(content);
        messageService.create(message);

        // 发送站内信

        return AppResult.success("发送成功");
    }

    @Operation(summary = "获取未读站内信数量")
    @GetMapping("/getUnreadCount")
    public AppResult<Integer> getUnreadCount(HttpServletRequest request) {
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        // 获取未读站内信数量
        Integer unreadCount = messageService.selectUnreadCount(user.getId());
        return AppResult.success(unreadCount);
    }

    @Operation(summary = "获取站内信列表")
    @GetMapping("/getAll")
    public AppResult getAll(HttpServletRequest request) {
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        List<Message> messages = messageService.selectByReceiveUserId(user.getId());
        // 获取站内信列表
        return AppResult.success(messages);
    }

    @Operation(summary = "更新为已读")
    @PostMapping("/markRead")
    public AppResult markRead(HttpServletRequest request,
                               @Param("站内信id") @RequestParam("id") @NonNull Long id) {
        // 根据id查询站内信
        Message message = messageService.selectById(id);
        if (message == null || message.getDeleteState() == 1) {
            return AppResult.failed(ResultCode.FAILED_MESSAGE_NOT_FOUND);
        }
        // 站内信是否自己的
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        if (!Objects.equals(message.getReceiveUserId(), user.getId())) {
            return AppResult.failed(ResultCode.FAILED_FORBIDDEN);
        }
        // 调用更新为已读的方法
        messageService.updateStateById(id, (byte) 1);
        return AppResult.success();
    }

    @Operation(summary = "更新为已回复")
    @PostMapping("/reply")
    public AppResult reply(HttpServletRequest request,
                               @Param("站内信id") @RequestParam("repliedId") @NonNull Long repliedId,
                                @Param("站内信内容") @RequestParam("content") @NonNull String content) {
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        if (user.getState() == 1) {
            // 用户已禁言
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        // 根据id查询站内信
        Message existsMessage = messageService.selectById(repliedId);
        if (existsMessage == null || existsMessage.getDeleteState() == 1) {
            return AppResult.failed(ResultCode.FAILED_MESSAGE_NOT_FOUND);
        }
        // 不能给自己回复
        if (user.getId().equals(existsMessage.getPostUserId())) {
            return AppResult.failed("不能给自己回复");
        }


        // 构造对象
        Message message = new Message();
        message.setPostUserId(user.getId());
        message.setReceiveUserId(existsMessage.getPostUserId());
        message.setContent(content);
        messageService.reply(repliedId,message);
        return AppResult.success();
    }
}
